class Collapse extends HTMLElement {
  constructor() {
    super();

    const shadow = this.attachShadow({mode: 'open'});
    const template = document.getElementById('myCollapse');
    const templateClone = template.content.cloneNode(true);

    const style  = document.createElement('style');
    // :host 表示影子元素的根元素
    style.textContent = `
      :host {
        display: flex;
        border: 1px solid;
        border-radius: 4px;
        width: 400px;
      }
      .my-collapse {
        width: 100%;
      }
    `;
    shadow.appendChild(style);
    shadow.appendChild(templateClone);

    const slot = shadow.querySelector('slot');
    slot.addEventListener('slotchange', (e) => {
      this.slotList = e.target.assignedElements();
      this.render();
    })
  }

  //  生命周期
  static get observedAttributes() { // 监控属性变化
    console.log('属性变化了');
    return ['active']
  }

  connectedCallback() { // 插入到DOM时
    console.log('插入到DOM时的回调');
  }

  disconnectedCallback() {
    console.log('移除DOM时的回调');
  }

  adoptedCallback() {
    console.log('将DOM移动到iframe时的回调');
  }

  attributeChangedCallback(key, oldVal, newVal) {
    console.log('属性值发生变化')
    if (key === 'active') {
      this.activeList = JSON.parse(newVal);
      this.render()
    }
  }

  render() {
    if (this.slotList && this.activeList) {
      [...this.slotList].forEach(child => {
        child.setAttribute('active', JSON.stringify(this.activeList))
      })
    }
  }
}

export default Collapse